
import router from '@/router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { message } from 'ant-design-vue'
import {eventBus} from "@/eventBus.ts";

let firstFetchLoginUser = true

/*
 * 全局权限校验
 */
router.beforeEach(async (to, from, next) => {

  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser
  // 确保页面刷新时，首次加载时，能等待后端返回用户信息后再校验权限
  if (firstFetchLoginUser) {
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
    firstFetchLoginUser = false
  }
  const toUrl = to.fullPath

  const publicPaths = [ '/user/login', '/user/register']

  // 自定义校验权限逻辑
  if (toUrl.startsWith('/admin')) {
    if (!loginUser || loginUser.userRole !== 'admin') {
      message.error('无权限访问')
      eventBus.emit('showLogin')
      return
    }
  }
  // console.log('access.ts beforeEach')
  // console.log(to.fullPath)
  // console.log(!loginUser?.id)
  // console.log(publicPaths.includes(toUrl))
  //
  // if (!loginUser && !publicPaths.includes(toUrl)) {
  //   console.log('loginUser', loginUser)
  //   // 如果用户未登录且访问非公开路径，则重定向到登录页面
  //   message.error('请先登录')
  //   next(`/user/login`)
  //   return
  // }
  // console.log(1)
  next()
})
